//
//  MTInfoVerificationViewController.swift
//  MT
//
//  Created by M on 2019/12/21.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory

/// 键盘
import IQKeyboardManagerSwift

/// 网络

import Moya
import Result
import RxSwift
import RxCocoa
/// nav
import YPNavigationBarTransition

class MTInfoVerificationViewController: BaseViewController {
    
//    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
//        .backgroundStyleTransparent
//    }
//    
//    override func yp_navigationBarTintColor() -> UIColor! {
//        UIColor(hex: 0xFFFFFF)
//    }
//
//    override func yp_navigationBackgroundColor() -> UIColor! {
//        .clear
//    }
//
//    override func yp_navigationBackgroundImage(withIdentifier identifier: AutoreleasingUnsafeMutablePointer<NSString?>!) -> UIImage! {
//        return nil
//    }
    
    /// MTProvider
    private lazy var provider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()    

    lazy var tableView: MTInfoVerificationTableView = {
        let tv = MTInfoVerificationTableView(frame: self.view.bounds)
        tv.verificationTask = self
        return tv
    }()
    
    var alertView: CenterAlertView?
    
    deinit {
        removeNotifications()
    }
}

// MARK: ------------------ Override ----------------------
extension MTInfoVerificationViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addNotifications()
        initializeUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        IQKeyboardManager.shared.enable = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if let a = alertView {
            a.dismiss()
            self.alertView = nil
        }
    }
    
}

// MARK: ------------------ 初始化 ----------------------
extension MTInfoVerificationViewController {
    
    private func initializeUI() {
        navigationItem.title = "基本信息"
        view.addSubview(tableView)
    }
    
}

// MARK: ------------------ 通知相关 ----------------------
extension MTInfoVerificationViewController {
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(shouldPresentPhotoLibrary), name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }

    private func removeNotifications() {
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension MTInfoVerificationViewController {
    
    private func shouldPresentPhotoLibrary() {
        let c = PhotoLibraryViewController()
        c.delegate = self
        c.allowVideoSelection = false
        c.maxSelectdCount = 1
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ PhotoLibraryViewControllerDelegate ----------------------
extension MTInfoVerificationViewController: PhotoLibraryViewControllerDelegate {
    
    func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
        tableView.imageAsset = asset
    }
    
}

// MARK: ------------------ 初始认证代理回调 MTInfoVerificationTableViewVerificationTask ----------------------
extension MTInfoVerificationViewController: MTInfoVerificationTableViewVerificationTask {
    
    func infoVerificationTableViewClickRule(selectValue: Int) {
        let c = MTMineWebViewController()
        c.selectValue = selectValue
        self.navigationController?.pushViewController(c, animated: true)
    }
    
    func infoVerificationTableView(_ tableView: MTInfoVerificationTableView, nickname: String, gender: LocalGenderModel.GenderType, birthday: String, location: String,isAgree: Bool) {
        
        if !isAgree {
            AlertManager.presentAlertView(message: "请勾选协议")
            return
        }
        
//        debugPrint("ajdlfjlaksd")
//        
//        if let a = alertView {
//            a.dismiss()
//            self.alertView = nil
//        }
//        
//        let a = AlertManager.presentAlertView(message: "请稍候", autoPresent: false)
//        a.isBackgroundCoverEnabled = true
//        a.backgroundCoverBackgroundColor = UIColor.black.withAlphaComponent(0.5)
//        a.isBackgroundCoverViewGestureEnabled = false
//        a.shouldAutoDismiss = false
//        a.isDismissButtonHidden = true
//        self.alertView = a
//        a.present()
        
        uploadInitializeUserInfos(nickname: nickname, gender: gender.requestType, birthday: birthday, location: location)
        /// 添加 indicator
//        _ = self.provider.originRequest(.upload(portrait), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in
//
//            /// 取消 indicator
//            guard let weakSelf = self else { return }
//            switch result {
//            case let .success(response):
//                guard let dict = try? response.mapJSON() as? [String:Any], let code = dict["code"] as? Int else { return }
//                if code == 200, let imageUrl = dict["result"] as? String  {
//                    weakSelf.uploadInitializeUserInfos(portrait: imageUrl, nickname: nickname, gender: gender.requestType, birthday: birthday, location: location)
//                } else {
//                    DispatchQueue.main.async {
//                        a.dismiss()
//                        AlertManager.presentAlertView(message: "上传头像失败")
//                    }
//                }
//                break
//
//            case let .failure(error):
//                DispatchQueue.main.async {
//                    a.dismiss()
//                    AlertManager.presentAlertView(message: error.localizedDescription)
//                }
//                break
//
//            }
//        }
    }
    
    private func uploadInitializeUserInfos(nickname: String, gender: Int, birthday: String, location: String) {
        
        let params: [String: Any] = [
                                     "address"      : location,
                                     "nickname"     : nickname,
                                     "birthday"     : birthday,
                                     "sex"          : gender]
        
        user_provider.originRequest(.initialization(params), callbackQueue: .global(), progress: nil) { [weak self] (result, _) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                weakSelf.alertView?.dismiss()
            }
            switch result {
            case .success(let response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200, let result = datas["result"] as? [String: Any] {
                        /// 刷新用户模型
                        UserCenter.default.set(with: result)
                        DispatchQueue.main.async {
                            guard let status = UserCenter.default.userStatus, let sex = UserCenter.default.sex else { return }
                            if sex == 0 {
                                
                                if let name = UserCenter.default.userName, let pwd = UserCenter.default.userPassword {
                                    IMLoginManager.login(name, pwd, complete: {
                                        /// 设置用户模型
                                        UserCenter.default.set(with: result)
                                        AlertManager.presentAlertView(message: "登录成功", duration: 1) {
                                            UserStatusNavigate.push(from: weakSelf, withUserStatus: status)
                                        }
                                    }) {
                                        UserCenter.default.clear()
                                        IMLoginManager.logout()
                                        AlertManager.presentAlertView(message: "登录失败")
                                    }
                                } else {
                                    UserCenter.default.logout()
                                }
                                
                            } else {
                                UserStatusNavigate.push(from: weakSelf, withUserStatus: status)
//                                let c = UIAlertController(title: "视频验证", message: "你将进入视频验证环节，是否进入", preferredStyle: .alert)
//                                let a1 = UIAlertAction(title: "是", style: .default) { (action) in
//                                    UserStatusNavigate.push(from: weakSelf, withUserStatus: status)
//                                }
//                                let a2 = UIAlertAction(title: "否", style: .cancel) { (action) in
//                                    weakSelf.navigationController?.popViewController(animated: true)
//                                }
//                                c.addAction(a1)
//                                c.addAction(a2)
//                                weakSelf.present(c, animated: true, completion: nil)
                                
                            }
                        }
                    } else {
                        DispatchQueue.main.async {
                            AlertManager.presentAlertView(message: "验证失败")
                        }
                    }
                    
                }
                break
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }
        
        
    }
    
}
